package cn.sycoder.controller;

import cn.sycoder.entity.Dept;
import cn.sycoder.entity.Product;
import cn.sycoder.entity.Role;
import cn.sycoder.entity.User;
import cn.sycoder.exception.BusinessException;
import cn.sycoder.exception.SystemException;
import cn.sycoder.mapper.DeptMapper;
import cn.sycoder.mapper.RoleMapper;
import cn.sycoder.mapper.UserMapper;
import cn.sycoder.resp.Code;
import cn.sycoder.service.IDeptService;
import cn.sycoder.service.IRoleService;
import cn.sycoder.service.IUserService;
import cn.sycoder.utils.Md5Utils;
import cn.sycoder.vo.DeptVo;
import cn.sycoder.vo.RoleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("/api")
@Api(tags = "用户管理")
@Transactional(rollbackFor = Exception.class)
public class UserController {

    @Autowired
    IUserService service;

    @Autowired
    UserMapper mapper;

    @Autowired
    IDeptService deptService; // 注入部门service

    @Autowired
    DeptMapper deptMapper;

    @Autowired
    IRoleService roleService;

    @Autowired
    RoleMapper roleMapper;

    @PostMapping("/User/list")
    @ApiOperation(value = "用户列表分页查询")
    public Map<String, Object> userList(@RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "10") int limit,
                                        @RequestParam(value = "userName", required = false) String userName,
                                        @RequestParam(value = "userMobile", required = false) String userMobile) {
        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        // 创建分页查询
        Page<User> objectPage = new Page<>(page, limit);

        // 构造sql
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        Map<String, Object> params = new HashMap<>();
        params.put("user_name", userName);
        params.put("user_mobile", userMobile);
        wrapper.allEq(params, false); // 如果条件中参数空值，则从条件中去除该参数

        try {
            // 执行分页查询，并返回结果
            IPage<User> userPage = mapper.selectPage(objectPage, wrapper);
            if (userPage != null) {
                // 获取用户总数
                long count = userPage.getTotal();
                response.put("count", count);
                response.put("data", userPage);
                response.put("success", true);
            } else {
                response.put("success", false);
                response.put("msg", "服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"处理业务异常，请稍后再试！");
        }

        return response;
    }


    @PostMapping("/User/save")
    @ApiOperation(value = "用户管理-保存（添加编辑）")
    public Map<String, Object> userSave(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "userName") String userName,
            @RequestParam(value = "userRealName") String userRealName,
            @RequestParam(value = "roleId") Long roleId,
            @RequestParam(value = "deptId") Long deptId,
            @RequestParam(value = "userMobile") String userMobile,
            @RequestParam(value = "userEmail") String userEmail,
            @RequestParam(value = "userSex") String userSex) {

        // 通过角色id查询角色名称
        String roleName = roleMapper.selectRoleName(roleId);
        String deptName = deptMapper.selectDeptName(deptId);

        HashMap<String, Object> response = new HashMap<>();
        User user = new User();
        user.setUserId(userId);
        user.setUserName(userName);
        user.setUserRealName(userRealName);
        user.setRoleId(roleId);
        user.setDeptId(deptId);
        user.setDeptName(deptName);
        user.setRoleName(roleName);
        user.setUserMobile(userMobile);
        user.setUserEmail(userEmail);
        user.setUserSex(userSex);
//        user.setUserPassword(userName); // 默认创建用户时，密码与账号同名
//        user.setEditTime(new Date());


        boolean ret = false;
        try {

            // 模拟一个条件来抛出异常
//            boolean simulateError = true; // 您可以根据需要设置这个条件
//            if (simulateError) {
//                throw new BusinessException(Code.BUSINESS_ERR);
//            }

            // 保存或更新方法
            if (userId != null) {
                // 有id表示更新操作
                ret = service.updateById(user);
            } else {
                // 无id表示保存操作
                ret = service.save(user);
            }
        }catch (BusinessException e){
            throw new BusinessException(Code.BUSINESS_ERR,"处理业务异常，请稍后再试！");
        }

        if (ret) {
            response.put("success", true);
        } else {
            response.put("msg", "服务器异常！");
        }
        return response;
    }


    @DeleteMapping("/User/delete")
    @ApiOperation(value = "用户管理-删除用户")
    public Map<String, Object> userDelete(@RequestParam String ids) {
        Map<String, Object> response = new HashMap<>();

        try {
            boolean ret = service.removeById(ids);
            if (ret) {
                response.put("success", true);
            } else {
                response.put("msg", "服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"处理业务异常，请稍后再试");
        }
        return response;
    }


    @PostMapping("/User/pwd")
    @ApiOperation(value = "用户管理-重置密码")
    public Map<String, Object> userPwd(@RequestParam Long userId) {

        Map<String, Object> response = new HashMap<>();
        User user = new User();
        user.setUserId(userId);
        user.setUserPassword(Md5Utils.hash("123456")); // 默认将密码重置为123456（使用Md5加密）

        try {
            boolean ret = service.updateById(user);

            if (ret) {
                response.put("success", true);
            } else {
                response.put("msg", "服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"处理业务异常，请稍后再试！");
        }
        return response;
    }


    @GetMapping("/UserDept/deptTree/{parentId}")
    @ApiOperation(value = "用户管理-获取部门设置")
    public Map<String, Object> userDeptTree(@PathVariable("parentId") Long parentId) {

        // 创建返回结果
        Map<String, Object> response = new HashMap<>();

        try {
            // 查询部门
            List<Dept> list = deptService.list();
            ArrayList<DeptVo> deptVo = new ArrayList<>();
            for (Dept dept : list) {
                DeptVo newDeptVo = new DeptVo();
                BeanUtils.copyProperties(dept, newDeptVo);
                deptVo.add(newDeptVo);
            }

            if (list != null) {
                response.put("success", true);
                response.put("data", deptVo);
            } else {
                response.put("success", false);
                response.put("msg", "服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"处理业务异常，请稍后再试！");
        }
        return response;
    }


    @PostMapping("User/change/dept")
    @ApiOperation(value = "用户管理-保存部门设置")
    public Map<String, Object> userChangeDept(@RequestParam("userIds") List<Long> Ids,
                                              @RequestParam Long deptId,
                                              @RequestParam String deptName) {

        // 创建返回结果
        Map<String, Object> response = new HashMap<>();

        int ret = 0;
        try {
            for (Long userId : Ids) {
                ret = mapper.updateByUserId(userId, deptId, deptName); // 遍历 userId 设置部门
            }

            // 返回结果
            if (ret > 0) {
                response.put("success", true);
            } else {
                response.put("msg", "服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"处理业务异常，请稍后再试！");
        }
        return response;
    }


    @GetMapping("/roleOptions")
    @ApiOperation(value = "获取用户角色列表")
    public Map<String, Object> fetchRoleOptions() {

        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        try {
            List<Role> list = roleService.list();

            ArrayList<RoleVo> roleVo = new ArrayList<>();
            for (Role role : list) {
                RoleVo newRoleVo = new RoleVo();
                BeanUtils.copyProperties(role, newRoleVo); // 实例对象拷贝，更改属性名与前端对应
                roleVo.add(newRoleVo);
            }

            if (roleVo != null){
                response.put("success",true);
                response.put("data", roleVo);
            }else {
                response.put("success",false);
                response.put("msg","服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"处理业务异常，请稍后再试！");
        }
        return response;
    }


    @GetMapping("/deptOptions")
    @ApiOperation(value = "获取用户部门列表")
    public Map<String, Object> fetchDeptOptions() {

        // 创建返回结果
        Map<String, Object> response = new HashMap<>();

        try {
            // 查询部门
            List<Dept> list = deptService.list();
            ArrayList<DeptVo> deptVo = new ArrayList<>();
            for (Dept dept : list) {
                DeptVo newDeptVo = new DeptVo();
                BeanUtils.copyProperties(dept, newDeptVo);
                deptVo.add(newDeptVo);
            }

            if (list != null) {
                response.put("success", true);
                response.put("data", deptVo);
            } else {
                response.put("success", false);
                response.put("msg", "服务器异常！");
            }
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"业务处理异常，请稍后再试！");
        }
        return response;
    }
}
